<template>
  <view class="container">
    <!-- 地图容器 -->
    <map
      id="map"
      class="map"
      :longitude="currentLongitude"
      :latitude="currentLatitude"
      :markers="markers"
      :scale="16"
      show-location
      @regionchange="handleMapChange"
    ></map>

    <!-- 中心指示标 -->
    <view class="center-marker">
      <image src="/static/location_marker.png" class="marker-icon" />
    </view>

    <!-- 显示选中坐标 -->
    <view class="location-card">
      <text>经度：{{ currentLongitude }}</text>
      <text>纬度：{{ currentLatitude }}</text>
    </view>
  </view>
  <button @click="savecation">确认位置</button>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import storage from '../../../utils/storage.js'
// 当前坐标
const currentLongitude = ref(116.397428)
const currentLatitude = ref(39.90923)
const markers = ref([])

// 获取设备位置
const getLocation = () => {

	console.log("onmened 获取位置");
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'wgs84',
      success: (res) => {
        currentLongitude.value = res.longitude
        currentLatitude.value = res.latitude
        updateMarker()
        resolve()
      },
      fail: (err) => {
        console.error('获取位置失败nmsl:', err)
        uni.showToast({ title: '请开启位置权限', icon: 'none' })
        reject(err)
      }
    })
  })
}
// 保存位置信息到全局
const savecation = async () =>{
		uni.setStorageSync("testKey",
		{
			currentLongitude:currentLongitude.value,
			currentLatitude:currentLatitude.value
		}
		)
		uni.navigateBack({
			delta:1,//返回层数，2则上上页
		})
}
// 更新地图标记
const updateMarker = () => {
  markers.value = [{
    id: 0,
    longitude: currentLongitude.value,
    latitude: currentLatitude.value,
    iconPath: '/static/location_pin.png',
    width: 32,
    height: 32
  }]
}

// 处理地图变化事件
let mapCtx = null
const handleMapChange = async (e) => {
  if (e.type === 'end') {
    if (!mapCtx) {
      mapCtx = await uni.createMapContext('map', this)
    }
    
    mapCtx.getCenterLocation({
      success: (res) => {
        currentLongitude.value = res.longitude
        currentLatitude.value = res.latitude
        updateMarker()
      }
    })
  }
}

onMounted(() => {
  // 初始化时获取位置
  getLocation()
})
</script>

<style scoped>
.container {
  position: relative;
  height: 100vh;
  width: 100vw;
}

.map {
  width: 100%;
  height: 100%;
}

.center-marker {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -100%);
}

.marker-icon {
  width: 40rpx;
  height: 64rpx;
}

.location-card {
  position: absolute;
  bottom: 30rpx;
  left: 20rpx;
  right: 20rpx;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}
</style>